import * as SQLite from 'expo-sqlite';
import { RecognitionHistoryItem } from '../utils/speechRecognition';

class DatabaseManager {
  private db: SQLite.SQLiteDatabase;
  private initialized: boolean = false;
  private initPromise: Promise<void>;

  constructor() {
    this.db = SQLite.openDatabaseSync('recognition.db');
    this.initPromise = this.initDB();
  }

  private async initDB() {
    if (this.initialized) return;
    
    try {
      await this.db.execAsync(`
        PRAGMA journal_mode = WAL;
        CREATE TABLE IF NOT EXISTS recognition_history (
          id INTEGER PRIMARY KEY AUTOINCREMENT,
          text TEXT NOT NULL,
          timestamp INTEGER NOT NULL,
          duration INTEGER,
          confidence INTEGER
        );
      `);
      this.initialized = true;
    } catch (error) {
      console.error('Failed to initialize database:', error);
      throw error;
    }
  }

  async saveRecognition(item: Omit<RecognitionHistoryItem, 'id'>): Promise<void> {
    await this.initPromise;
    await this.db.runAsync(
      'INSERT INTO recognition_history (text, timestamp, duration, confidence) VALUES (?, ?, ?, ?)',
      [item.text, item.timestamp, item.duration || null, item.confidence || null]
    );
  }

  async getHistory(limit = 50): Promise<RecognitionHistoryItem[]> {
    await this.initPromise;
    return await this.db.getAllAsync<RecognitionHistoryItem>(
      'SELECT * FROM recognition_history ORDER BY timestamp DESC LIMIT ?',
      [limit]
    );
  }
}

export const dbManager = new DatabaseManager(); 